#!/bin/bash

script_dir()
{
    SOURCE="${BASH_SOURCE[0]}"
    while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink
	DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
	SOURCE="$(readlink "$SOURCE")"
	[[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE"
    done
    DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
    echo ${DIR}
}


export PRODUCT_VERSION=@projectVersion@
export PRODUCT_COMMIT=@gitCommit@
export PRODUCT_COMMIT_TIME=@gitCommitTime@
export PRODUCT_BUILD_TIME=@gitBuildTime@

export PRODUCT_HOME="$( script_dir )"
export PRODUCT_JAR=${PRODUCT_HOME}/hna-iot-server-${PRODUCT_VERSION}.jar

echo ""
echo "PRODUCT_HOME: $PRODUCT_HOME"
echo "PRODUCT_LOG: $PRODUCT_HOME/logs"
echo "PRODUCT_BUILD_INFO:"
echo "------------------------------------------------------"
echo "| Version: $PRODUCT_VERSION"
echo "| Build Time: $PRODUCT_BUILD_TIME"
echo "| Commit Time: $PRODUCT_COMMIT_TIME"
echo "| Git Commit: $PRODUCT_COMMIT"
echo "------------------------------------------------------"

# mode: fg - foreground, otherwise in background
mode=$1
JAVA_OPTIONS="$JAVA_OPTIONS -Dfile.encoding=UTF8"
JAVA_OPTIONS="$JAVA_OPTIONS -Xms1G -Xmx1G -XX:+UseG1GC"
JAVA_OPTIONS="$JAVA_OPTIONS -XX:+UseCompressedOops -XX:+OptimizeStringConcat"

PIDFILE=${PRODUCT_HOME}/@pidfile@

if [[ -f ${PIDFILE} ]]
then
   echo "Iot Server is already running with PID: `cat ${PIDFILE}`"
   echo ""
   exit 1
fi

if [[ "${mode}" = "fg" ]]
then
   echo  "Starting Iot Server in foreground in [@activeProfile@] mode..."
   java ${JAVA_OPTIONS} -jar ${PRODUCT_JAR}
else
   nohup java ${JAVA_OPTIONS}  -jar ${PRODUCT_JAR} > /dev/null 2>&1 &
   echo  "Iot Server will be started in background in [@activeProfile@] mode."
   echo  "Check logs at ${PRODUCT_LOG} for details."
fi
echo ""